package com.funmi.lizip.security.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.funmi.lizip.entity.AdminUser;
import com.funmi.lizip.entity.User;
import com.funmi.lizip.mapper.AdminUserMapper;
import com.funmi.lizip.mapper.UserMapper;
import com.funmi.lizip.security.entity.SecurityAdminUser;
import com.funmi.lizip.security.entity.SecurityUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

@Slf4j
public class ClimbUserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    /*@Autowired
    private UserDetailsService userDetailsService;*/

    @Autowired
    private AdminUserMapper adminUserMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 从数据源中读取用户信息
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            QueryWrapper<AdminUser> adminUserQueryWrapper = new QueryWrapper<>();
            adminUserQueryWrapper.eq("username", username)
                    .eq("is_delete", 0);
            AdminUser adminUser = adminUserMapper.selectOne(adminUserQueryWrapper);
            if (adminUser == null) {
                throw new UsernameNotFoundException(String.format("用户['%s']不存在", username));
            }
            return new SecurityAdminUser(adminUser, null, null);
        }

        /*// 读取用户的所有角色
        List<Role> roleList = userMapper.selectRoleForUsername(user.getId());
        // 读取用户的所有权限
        List<Permission> permissionList = userMapper.selectPermissionForUsername(user.getId());
		// 构造security用户
		return new SecurityUser(user, roleList, permissionList)*/;
        return new SecurityUser(user, null, null);
    }
}